package com.luych.toolbox.gateway.center.listener;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.luych.toolbox.common.event.base.service.WebSocketLetterRemoteApplicationEvent;
import com.luych.toolbox.common.feign.intf.base.service.LetterFeign;
import com.luych.toolbox.common.feign.param.base.service.LetterParam;
import com.luych.toolbox.gateway.center.websocket.WebSocketEndPoint;
import com.luych.toolbox.gateway.center.websocket.WebSocketMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.UUID;

@Component
public class WebSocketLetterListener implements ApplicationListener<WebSocketLetterRemoteApplicationEvent> {

    private static final Logger logger = LoggerFactory.getLogger(WebSocketLetterListener.class);

    private final ObjectMapper objectMapper;
    private final LetterFeign letterFeign;
    private final WebSocketEndPoint webSocketEndPoint;

    @Autowired
    public WebSocketLetterListener(ObjectMapper objectMapper, LetterFeign letterFeign, WebSocketEndPoint webSocketEndPoint) {
        this.objectMapper = objectMapper;
        this.letterFeign = letterFeign;
        this.webSocketEndPoint = webSocketEndPoint;
    }

    @Override
    public void onApplicationEvent(WebSocketLetterRemoteApplicationEvent event) {
        if (StringUtils.isEmpty(event.getLetter().getId())) {
            event.getLetter().setId(UUID.randomUUID().toString());
        }

        LetterParam letter = new LetterParam();
        letter.setId(event.getLetter().getId());
        letter.setUserId(event.getUserId());
        letter.setType(event.getLetter().getType());
        letter.setMessage(event.getLetter().getMessage());
        letter.setContent(event.getLetter().getContent());
        letterFeign.create(letter);

        WebSocketMessage message = new WebSocketMessage(event.getLetter());
        try {
            webSocketEndPoint.onSend(event.getUserId(), objectMapper.writeValueAsString(message));
        } catch (IOException e) {
            logger.error("websocket send letter, userId: {}, error: {}", event.getUserId(), e.getMessage(), e);
        }
    }
}
